package com.ws.shop.app;

import java.io.File; 
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException; //import org.dom4j.Node;

import com.ws.shop.util.Dom4JUtil;
import com.ws.shop.util.Tools;



public class Config extends Thread {

	private static final String CONFIG_DIR = "com/ws/shop/app/jp.xml";

	private static File file;

	private static Document doc;

	private int timeout;// 超时时间

	private String logconfig;// 日志配置文件

	private String backupsrc;// 文件备份

	private String suffix; // 标识hontootrule配置程序（现生产上部署了多个hontooturle程序）

	private int threadCount; // 进程上线数

	private String worksrc; // 工作目录

	private String inputdir; // 输入目录---用来接受用户激活的文件，用来分配

	private int sleeptime = 5; // 扫描一次文件休眠的时间

	private String err; // 错误目录


	protected static org.apache.log4j.Logger cat = org.apache.log4j.Logger
			.getLogger(Config.class.getName());

	private static final Config m_config = new Config();

	private static boolean isNewThread = false;

	private Config() {
		try {
			ini();
			start();// 启动监控线程
		} catch (Exception e) {
			cat.error("---------- Config init Error ::"
					+ Tools.getStackTrace(e));
			e.printStackTrace();
		}
	}

	public static Config getInstance() {
		return m_config;
	}

	public void run() {

		// 如果已经新开了线程，本线程就退出
		if (isNewThread) {
			return;
		}

		// 标记为已经新增了监控线程
		isNewThread = true;

		long lastModified = file.lastModified();
		while (true) {
			try {
				Thread.sleep(1000 * 60 * 5);
				if (lastModified != file.lastModified()) {
					lastModified = file.lastModified();
					m_config.ini();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void ini() throws Exception {
		cat.info("---------- Config is Init ----------");

		file = new File(Thread.currentThread().getContextClassLoader()
				.getResource(CONFIG_DIR).getFile());

		// 把文件转成DOC
		doc = Dom4JUtil.parseWithSAX(file);

		// 超时时间
		timeout = Integer.parseInt(doc.valueOf("//application/timeout").trim());

		// 日志路径
		String logConfigDir = "com/ws/shop/app/"
				+ doc.valueOf("//application/logconfig").trim();
		logconfig = Thread.currentThread().getContextClassLoader().getResource(
				logConfigDir).getFile();

		// 区域应答备份
		backupsrc = doc.valueOf("//application/backupsrc").trim();

		// hontoot程序标识
		suffix = doc.valueOf("//application/suffix").trim();

		// 线程数上线
		String tc = doc.valueOf("//application/threadcount").trim();
		if (tc == null || tc.equals(""))
			tc = "500";
		threadCount = Integer.parseInt(tc);

		worksrc = doc.valueOf("//application/worksrc").trim();

		// 接受激活 文件的 输入目录
		inputdir = doc.valueOf("//application/inputdir").trim();
		err = doc.valueOf("//application/err").trim();
		try {
			sleeptime = Integer.parseInt(doc.valueOf("//application/sleeptime")
					.trim());
		} catch (Exception ex) {
			sleeptime = 0;
		}

	}

	public int getTimeout() {
		return timeout;
	}


	public String getLogconfig() {
		return logconfig;
	}

	public String getbackupsrc() {
		return backupsrc;
	}

	public static String valueOf(Document document, String key) {
		return document.valueOf(key);
	}

	public static String valueOf(String key) {
		if (doc == null) {
			try {
				doc = Dom4JUtil.parseWithSAX(file);
			} catch (DocumentException e) {
				cat.error("---------- Parsing Config File Error ::"
						+ Tools.getStackTrace(e));
			}
		}
		return doc.valueOf(key);
	}

	public int getThreadCount() {
		return threadCount;
	}

	public static Document getDoc() {
		return doc;
	}

	public static void setDoc(Document doc) {
		Config.doc = doc;
	}

	public String getWorksrc() {
		return worksrc;
	}

	public String getSuffix() {
		return suffix;
	}

	public String getInputdir() {
		return inputdir;
	}

	public void setInputdir(String inputdir) {
		this.inputdir = inputdir;
	}

	public int getSleeptime() {
		return sleeptime;
	}


	public String getErr() {
		return err;
	}

	public static Map<Object,Object> sortMapByKey(Map<Object,Object> map) {   
        Map<Object, Object> mapVK = new TreeMap<Object, Object>(   
                new Comparator<Object>() {   
                    public int compare(Object obj1, Object obj2) {   
                        String v1 = (String) obj1;   
                        String v2 = (String) obj2;   
                        int s = v1.compareTo(v2);   
                        return s;   
                    }   
                });   
        Set<Object> col = map.keySet();   
        Iterator<Object> iter = col.iterator();
        while (iter.hasNext()) {   
            String key = (String) iter.next();   
            String value = (String) map.get(key);   
            mapVK.put(key, value);   
        }   
        return mapVK;   
    }

	
}
